import 'dart:math';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/expert/expert_record_entity.dart';
import 'package:ball_lion/entity/match/expert_views_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/server/api/expert_api.dart';
import 'package:ball_lion/utils/mode_config.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/expert/expert_rate_chart.dart';
import 'package:ball_lion/module/expert/items/plan_item.dart';
import 'package:ball_lion/module/widget/history_label.dart';
import 'package:ball_lion/widgets/card.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
// import 'package:ball_lion/module/pick/expert_list_item.dart';

class UserViewPointList extends StatefulWidget {
  //1 足球 2篮球
  final int type;
  final String expertId;
  final bool isShare;
  const UserViewPointList(this.type, this.expertId,
      {super.key, this.isShare = false});

  @override
  State<UserViewPointList> createState() => _UserViewPointListState();
}

class _UserViewPointListState extends State<UserViewPointList>
    with AutomaticKeepAliveClientMixin {
  List<PlanEntity>? planHistory;
  List<PlanEntity>? planNew;
  ExpertRecordEntity? record;
  EasyRefreshController refreshC =
      EasyRefreshController(controlFinishLoad: true);
  int page = 1;
  int pageSize = 30;

  final List<String> statusImage = [
    "",
    "viewpoint_status1.png",
    "viewpoint_status2.png",
    "viewpoint_status3.png",
    "viewpoint_status4.png",
    "viewpoint_status5.png",
    "viewpoint_status6.png",
    "viewpoint_status7.png"
  ];

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return widget.isShare
        ? Column(
            children: [
              if (ModeConfig.expertRecord) ...[
                ExpertRateChart(
                    expertId: widget.expertId, sportId: widget.type),
                if (record?.achievement.hasValue == true) _expertRecordWidget(),
              ]
            ],
          )
        : MediaQuery.removePadding(
            context: context,
            removeTop: true,
            child: Container(
              color: Colours.greyF2F3F7,
              child: EasyRefresh(
                controller: refreshC,
                footer:
                    Styles.refreshFooter(position: IndicatorPosition.locator),
                onRefresh: () async => await getData(),
                onLoad: () async => await getMore(),
                child: LoadingWidget<bool>(
                  isLoading: planNew == null || planHistory == null,
                  data: planNew?.length == 0 && planHistory?.length == 0,
                  child: () => CustomScrollView(
                    slivers: [
                      if (ModeConfig.expertRecord) ...[
                        SliverToBoxAdapter(
                            child: ExpertRateChart(
                                expertId: widget.expertId,
                                sportId: widget.type)),
                        if (record?.achievement.hasValue == true)
                          SliverToBoxAdapter(child: _expertRecordWidget()),
                      ],
                      if (planNew.hasValue) ...[
                        SliverToBoxAdapter(
                            child: Container(
                          padding: const EdgeInsets.only(left: 12, top: 16),
                          margin: const EdgeInsets.fromLTRB(8, 8, 8, 0),
                          decoration: const BoxDecoration(
                              color: Colours.white,
                              borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(8),
                                  topRight: Radius.circular(8))),
                          child: QsText("最新方案（${planNew?.length ?? 0}）",
                              fontSize: 16, fontWeight: FontWeight.w600),
                        )),
                        SliverList(
                            delegate: SliverChildBuilderDelegate(
                                childCount: planNew?.length ?? 0,
                                (context, index) {
                          return _expertNewViewsWidget(index);
                        })),
                      ],
                      if (planHistory.hasValue) ...[
                        SliverToBoxAdapter(
                          child: Container(
                            padding: const EdgeInsets.only(left: 12, top: 16),
                            margin: const EdgeInsets.fromLTRB(8, 8, 8, 0),
                            decoration: const BoxDecoration(
                                color: Colours.white,
                                borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(8),
                                    topRight: Radius.circular(8))),
                            child: const QsText("历史方案",
                                fontSize: 16, fontWeight: FontWeight.w600),
                          ),
                        ),
                        SliverList(
                            delegate: SliverChildBuilderDelegate(
                                childCount: planHistory!.length,
                                (context, childIndex) {
                          return _expertHistoryViewsWidget(childIndex);
                        }))
                      ],
                      const FooterLocator.sliver(),
                      SliverToBoxAdapter(child: Container(height: 80))
                    ],
                  ),
                ),
              ),
            ),
          );
  }

  getData() async {
    // if (page == 1) {
    //   planHistory = [];
    // }
    // List planHistory = [];
    ExpertApi.getExpertNewViews(widget.expertId, widget.type).then((value) {
      if (value != null) {
        planNew = value;
        update();
      }
    });
    ExpertApi.getExpertRecord(widget.expertId, widget.type).then((value) {
      if (value != null) {
        record = value as ExpertRecordEntity?;
        update();
      }
    });
    page = 1;
    final result = await ExpertApi.getPlanHistory(
        widget.expertId, widget.type, page, pageSize);
    if (result != null) {
      planHistory = result;
      refreshC.resetFooter();
    }

    update();
  }

  getMore() async {
    page++;
    final result = await ExpertApi.getPlanHistory(
        widget.expertId, widget.type, page, pageSize);
    if (result != null) {
      planHistory!.addAll(result);
      refreshC.finishLoad(result.length < pageSize
          ? IndicatorResult.noMore
          : IndicatorResult.success);
      update();
    }
  }

  Widget _expertRecordWidget() {
    var list = [
      record!.redKeep == null || record!.redKeep == '' || record!.redKeep == '-'
          ? '-'
          : record!.redKeep,
      record!.backRatioNew == null ||
              record!.backRatioNew == '' ||
              record!.backRatioNew == '-'
          ? '-'
          : "${double.parse(record!.backRatioNew!).toInt()}%",
      record!.redKeepHigh == null ||
              record!.redKeepHigh == '' ||
              record!.redKeepHigh == '-'
          ? '-'
          : record!.redKeepHigh,
    ];
    List<String> recordTypeList = ["当前状态", "近n场回报", "最高连红"];
    return Block(
      cardStyle: const CardStyle(
        padding: EdgeInsets.all(16),
        margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          QsText("${widget.type == 1 ? "足球" : "篮球"}战绩",
              fontSize: 16, fontWeight: FontWeight.w600),
          Container(height: 9),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: List<Widget>.generate(
                3,
                (childIndex) => Expanded(
                      child: Container(
                        height: 66,
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        decoration: BoxDecoration(
                          color: Colours.greyF5F7FA,
                          borderRadius: BorderRadius.circular(5.0),
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            QsText(list[childIndex]!,
                                fontSize: 16,
                                color: Colours.main,
                                fontWeight: FontWeight.w500),
                            QsText(
                                childIndex == 1
                                    ? "近${record!.backRatioMNew ?? "n"}单回报"
                                    : recordTypeList[childIndex],
                                fontSize: 12)
                          ],
                        ),
                      ),
                    )).insertEvery(Container(width: 8)),
          ),
          Container(height: 7),
          if (record?.achievement.hasValue == true)
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              physics: const ClampingScrollPhysics(),
              child: Row(
                children: List.generate(
                  record!.achievement!.length,
                  (index) => Padding(
                    padding: const EdgeInsets.only(right: 8),
                    child: _buildAchievementList(index),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _expertNewViewsWidget(int index) {
    return Container(
        margin: const EdgeInsets.symmetric(horizontal: 8),
        padding: const EdgeInsets.symmetric(horizontal: 12),
        clipBehavior: Clip.hardEdge,
        decoration: BoxDecoration(
            color: Colours.white,
            borderRadius: index == planNew!.length - 1
                ? const BorderRadius.only(
                    bottomLeft: Radius.circular(8),
                    bottomRight: Radius.circular(8))
                : null),
        child: Column(
          children: [
            PlanItem(isExpertDetailView: true, entity: planNew![index]),
            if (index != planNew!.length - 1)
              Container(
                height: 0.5,
                width: double.infinity,
                color: Colours.greyEE,
              )
          ],
        ));
  }

  Widget _expertHistoryViewsWidget(int index) {
    return Container(
        margin: const EdgeInsets.symmetric(horizontal: 8),
        padding: const EdgeInsets.symmetric(horizontal: 12),
        clipBehavior: Clip.hardEdge,
        decoration: BoxDecoration(
            color: Colours.white,
            borderRadius: index == planHistory!.length - 1
                ? const BorderRadius.only(
                    bottomLeft: Radius.circular(8),
                    bottomRight: Radius.circular(8))
                : null),
        child: Column(
          children: [
            PlanItem(
              isExpertDetailView: true,
              entity: planHistory![index],
              eventType: "expert_detail_plan_view",
            ),
            if (index != planHistory!.length - 1)
              Container(
                height: 0.5,
                width: double.infinity,
                color: Colours.greyEE,
              )
          ],
        ));
  }

  Widget _buildAchievementList(int childIndex) {
    var achievement = record!.achievement![childIndex];
    return Transform.rotate(
      angle: pi / 6,
      child: HistoryLabel.viewpointRecord(
        state: achievement.status,
        width: 28,
        fontSize: 10,
      ).tap(() => Get.toNamed(Routes.viewpoint, arguments: achievement.planId)),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
